package com.example.lvsuo.proxy;

import com.example.lvsuo.annotation.Redis;
import com.example.lvsuo.modal.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class RedisProxy {
    @Autowired
    RedisTemplate<Object,Object> rt;

    @Around("@annotation(r)")
    public Result around(ProceedingJoinPoint jp, Redis r) throws Throwable {
        String s=r.value();
        if(("").equals(s)){
            throw new Exception("缓存注解必须传入表名！");
        }
        Object o = rt.opsForValue().get(s);
        if(o==null){
            o = jp.proceed();
            rt.opsForValue().set(s,o,30, TimeUnit.MINUTES);//一小时过期
        }
        return Result.back(o);
    }
}
